import { Modal, Table, Input } from 'antd';
import { PlusCircleOutlined } from '@ant-design/icons';
import { useState, useEffect, useRef } from 'react';
import ProcessGroupSelectItem from './ProcessGroupSelectItem';
import type { ColumnsType } from 'antd/es/table';
import { getProcessGroupSelector } from '../servers';
import Pagination from '@inbiz/basic/Pagination';
import { InbizIcon,deepClone } from '@inbiz/utils';
import { TextWidget, getMessage } from '@inbiz/react';
import './style.less';

interface DataType {
  key: React.Key;
  groupId: string;
  groupName: string;
  pageIndex: string;
  pageSize: string;
}

const ProcessGroupSelector = (props: any) => {
  const ref: any = useRef();
  const { onChange, value } = props;
  const [selectedGroup, setSelectedGroup] = useState<DataType[]>(value || []);
  const [ProcessGroup, setProcessGroup] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>(
    value ? value?.map((item: { groupId: string }) => item?.groupId) : []
  );
  const [ProcessGroupList, setProcessGroupList] = useState([]);
  const [GroupListTotal, setGroupListTotal] = useState(0);
  const [groupName, setGroupName] = useState('');
  const [pageIndex, setPageIndex] = useState<any>(1);
  const [pageSize, setPageSize] = useState<any>(20);

  //分组弹窗列
  const columns: ColumnsType<DataType> = [
    {
      title: '分组名称',
      dataIndex: 'groupName',
      key: 'groupName',
      render: (txt: string) => {
        return <TextWidget>{txt}</TextWidget>;
      },
      onCell: (rec: any) => {
        return {
          title: getMessage(rec?.groupName)
        }
      }
    },
    {
      title: '是否可见',
      dataIndex: 'isShow',
      key: 'isShow',
      render: (r) => {
        if (r === 1) {
          return '否';
        } else if (r === 0) {
          return '是';
        }
      },
    },
  ];

  //分组弹窗数据接口
  const getProcessGroupList = (
    groupName: string,
    pageIndex: number,
    pageSize: number,
  ) => {
    getProcessGroupSelector({
      groupName: groupName,
      pageIndex: pageIndex,
      pageSize: pageSize,
    }).then((res: any) => {
      let result = res?.details?.rows;
      let result1 = res?.details?.total;
      if (res?.code == 200 && res?.details) {
        setProcessGroupList(result);
        setGroupListTotal(result1);
      } else {
        setProcessGroupList([]);
        setGroupListTotal(0);
      }
    });
  };

  //监听分页
  useEffect(() => {
    getProcessGroupList(groupName, pageIndex, pageSize);
  }, [groupName, pageIndex, pageSize]);

  //监听查询
  useEffect(() => {
    setPageIndex(1);
  }, [groupName]);

  //点击按钮搜索
  const handleClick = (data: any) => {
    if (ref) {
      setGroupName(data);
    }
  };

  //回车搜索
  const onPressEnter = (e: any) => {
    setGroupName(e?.target?.value);
  };

  const handleRowClick = (RowKeys: any[] | ((prevState: string[]) => string[]), Rows: any[] | ((prevState: DataType[]) => DataType[])) => {
    setSelectedRowKeys(RowKeys);
    setSelectedGroup(Rows);
  };

  const onOk = () => {
    onChange(selectedGroup);
    setProcessGroup(false);
  };

  const handleRowSelection = (record: any) => {
    const existKey = selectedRowKeys.includes(record.groupId);
    if (existKey) {
      const newkeys = deepClone(selectedRowKeys);
      const newrows = deepClone(selectedGroup);
      const index = selectedRowKeys.indexOf(record.groupId);
      newkeys.splice(index, 1);
      newrows.splice(index, 1);
      handleRowClick(newkeys, newrows);
    } else {
      handleRowClick([...selectedRowKeys, record.groupId], [...selectedGroup, record]);
    }
  };

  return (
    <>
      <div className="process-group-selector-wrapper">
        <div className="process-group-selector-selected">
          {value?.map((item: any) => {
            return (
              <ProcessGroupSelectItem
                key={item.groupId}
                item={item}
                onChange={onChange}
                selectedGroup={selectedGroup}
                setSelectedGroup={setSelectedGroup}
                setSelectedRowKeys={setSelectedRowKeys}
              />
            );
          })}
        </div>
        <div className="process-group-selector-icon">
          {/* @ts-ignore */}
          <PlusCircleOutlined
            onClick={() => {
              setProcessGroup(true);
            }}
          />
        </div>

        {/* 分组弹窗 */}
        <Modal
          width={500}
          bodyStyle={{ width: 500, maxHeight: 400 }}
          title="分组"
          visible={ProcessGroup}
          centered={true}
          onOk={onOk}
          onCancel={() => setProcessGroup(false)}
        >
          <div className="process-group-modal">
            <div className="process-group-listTable">
              <div
                className="process-group-input"
                style={{
                  position: 'relative',
                }}
              >
                <Input
                  ref={ref}
                  placeholder="请输入分组名称"
                  onPressEnter={onPressEnter}
                  style={{
                    width: 300,
                    margin: '10px 0',
                  }}
                />
                <InbizIcon
                  type="icon-inbiz_basic-search"
                  onClick={() => handleClick(ref?.current?.input?.value)}
                  style={{
                    color: '#d9d9d9',
                    position: 'absolute',
                    top: 19,
                    left: 275,
                  }}
                />
              </div>
              <div className="process-group-table">
                <Table
                  scroll={{
                    y: 260,
                  }}
                  pagination={false}
                  size="small"
                  bordered={true}
                  columns={columns}
                  dataSource={ProcessGroupList}
                  rowKey={'groupId'}
                  rowSelection={{
                    selectedRowKeys,
                    onSelect: (record) => {
                      handleRowSelection(record);
                    },
                    onSelectAll: (selected, _selectedRows, changeRows: any) => {
                      if(!selected){
                        let _dataSource = ProcessGroupList?.map((item: any) => item?.groupId);
                        let _selectedRowKeys = selectedRowKeys?.filter((item2: string) => !_dataSource?.includes(item2));
                        let __selectedRows = selectedGroup?.filter((item3: any) => _selectedRowKeys?.includes(item3?.groupId));
                        handleRowClick(_selectedRowKeys, __selectedRows);
                      } else {
                        let __selectedRows = selectedGroup?.concat(changeRows);
                        const newArr = new Set(__selectedRows);
                        __selectedRows = [...newArr];
                        let _keys = __selectedRows?.map(item => item?.groupId);
                        handleRowClick(_keys, __selectedRows);
                      }
                    },
                  }}
                  onRow={(record:any) => {
                    return {
                      onClick: () => {
                        handleRowSelection(record);
                      },
                    };
                  }}
                />
                <Pagination
                  size="small"
                  total={GroupListTotal}
                  current={pageIndex}
                  pageSize={pageSize}
                  onChange={(page: any) => {
                    setPageIndex(page.current);
                    setPageSize(page.pageSize);
                  }}
                />
              </div>
            </div>
          </div>
        </Modal>
      </div>
    </>
  );
};
export default ProcessGroupSelector;
